package com.tanhua.dubbo.api.impl;
import org.bson.types.ObjectId;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.UserLikeVo;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserLikeApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RecommendUserApi recommendUserApi;

    @Override
    public void addLove(Long userId, Long likeUserId) {
        UserLike userLike = new UserLike();
//        userLike.setId(new ObjectId());
        userLike.setUserId(userId);
        userLike.setLikeUserId(likeUserId);
        userLike.setCreated(System.currentTimeMillis());
        mongoTemplate.save(userLike);
    }

    @Override
    // db.tanhua_users.count({userId:1})
    public Long queryEachLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);
        return count;
    }

    @Override
    // db.user_like.count({userId:1})
    public Long queryLoveCount(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return count;
    }

    @Override
    // db.user_like.count({likeUserId:1})
    public Long queryFanCount(Long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        long count = mongoTemplate.count(query, UserLike.class);
        return count;
    }

    @Override
    public PageResult queryEachLoveList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1) * pagesize);

        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        long count = mongoTemplate.count(query, Friend.class);

        // 将当前页的数据转为list<vo>
        List<UserLikeVo> voList = new ArrayList<>();

        if (friendList != null) {
            for (Friend friend : friendList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();
                // 封装vo
                vo.setId(friend.getFriendId()); // 设置好友id
                Long score = recommendUserApi.queryScore(userId, friend.getFriendId());
                vo.setMatchRate(score.intValue());
                // 添加vo
                voList.add(vo);
            }
        }
        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    public PageResult queryLoveList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1) * pagesize);

        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        // 将当前页的数据转为list<vo>
        List<UserLikeVo> voList = new ArrayList<>();

        if (userLikeList != null) {
            for (UserLike userLike : userLikeList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();
                // 封装vo
                vo.setId(userLike.getLikeUserId()); // 设置喜欢的人id
                Long score = recommendUserApi.queryScore(userId, userLike.getLikeUserId());
                vo.setMatchRate(score.intValue());
                // 添加vo
                voList.add(vo);
            }
        }
        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    public PageResult queryFanList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created")));
        query.limit(pagesize).skip((page - 1) * pagesize);

        List<UserLike> userLikeList = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        // 将当前页的数据转为list<vo>
        List<UserLikeVo> voList = new ArrayList<>();

        if (userLikeList != null) {
            for (UserLike userLike : userLikeList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();
                // 封装vo
                vo.setId(userLike.getUserId()); // 设置粉丝的id
                Long score = recommendUserApi.queryScore(userId, userLike.getUserId());
                vo.setMatchRate(score.intValue());
                // 添加vo
                voList.add(vo);
            }
        }
        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    public PageResult queryVisitorList(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(pagesize).skip((page - 1) * pagesize);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        long count = mongoTemplate.count(query, Visitors.class);

        // 将当前页的数据转为list<vo>
        List<UserLikeVo> voList = new ArrayList<>();

        if (visitorsList != null) {
            for (Visitors visitors : visitorsList) {
                // 创建vo
                UserLikeVo vo = new UserLikeVo();
                // 封装vo
                vo.setId(visitors.getVisitorUserId()); // 设置访客的id
                Long score = recommendUserApi.queryScore(userId, visitors.getVisitorUserId());
                vo.setMatchRate(score.intValue());
                // 添加vo
                voList.add(vo);
            }
        }
        return new PageResult(page, pagesize, (int) count, voList);
    }

    @Override
    // db.user_like.remove({userId:3, likeUserId:20})
    public void delete(Long userId, Long uid) {
        Query query = new Query(Criteria.where("userId").is(uid).and("likeUserId").is(userId));
        mongoTemplate.remove(query, UserLike.class);
    }

    @Override
    public Boolean ifCount(Long userId, Long likeUserId) {
        //判断likeUserId是否喜欢userId 即是否存在
        Query query = new Query(Criteria.where("userId").is(userId)
        .and("likeUserId").is(likeUserId));
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        if (userLike == null) {
            return false;
        }
        return true;
    }

    /**
     * 查询我的粉丝
     *
     * @param userId          用户Id
     * @param recommendUserId 推荐用户Id
     */
    @Override
    public UserLike queryUserFanList(Long userId, Long recommendUserId) {
        // 1.查询偶像是不是用户Id
        Query query = new Query(Criteria.where("likeUserId").is(userId).and("userId").is(recommendUserId));
        // 2.根据用户Id查出粉丝
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
        // 3.返回粉丝对象
        return userLike;

    }

    /**
     * 添加喜欢
     *
     * @param userId          用户Id
     * @param recommendUserId 推荐用户Id
     */
    @Override
    public void saveFans(Long userId, Long recommendUserId) {

        UserLike userLike = new UserLike();
        userLike.setUserId(userId);
        userLike.setLikeUserId(recommendUserId);
        userLike.setCreated(System.currentTimeMillis());

        // 保存
        mongoTemplate.save(userLike);

    }

    //喜欢 - 取消
    @Override
    public void cancelLike(Long userId, Long uid) {
        Query query = new Query(Criteria.where("userId").is(userId).and("friendId").is(uid));
        Friend friend = mongoTemplate.findOne(query, Friend.class);
        if(friend!=null){
            mongoTemplate.remove(query,Friend.class);
            query = new Query(Criteria.where("userId").is(uid).and("friendId").is(userId));
            mongoTemplate.remove(query,Friend.class);
            UserLike userLike = new UserLike();
            userLike.setUserId(uid);
            userLike.setLikeUserId(userId);
            userLike.setCreated(System.currentTimeMillis());
            mongoTemplate.save(userLike);
        }else {
            query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(uid));
            mongoTemplate.remove(query,UserLike.class);
        }
    }
}
